<script setup lang="ts">
import {ref} from "vue"
import {TipMessageTypeConst, useTipStore, StnIptProvider} from "st-ui-vue3-navie"
import {ResType, ResObjPropNameConst} from "st-common-req"
import {ManagerTable} from '@components'
import {useLoadingStore} from "@loading"
import {delMenus, MenuType} from "@menu"
import {MenuTableCols} from "../consts/menu-table-cols.ts"
import MenuInfoEditor from "../components/MenuInfoEditor.vue"
import {MenuFormDefault} from "../consts/menu-form-default.ts"
import {useSysMenuStore} from '../stores/sys-menu-store.ts'
import MenuSearch from '../components/MenuSearch.vue'
import {MenuIptProps} from '../consts/menu-ipt-props.ts'

/**
 * 菜单信息编辑
 */
// 菜单信息表单对象
const menuInfoForm = ref<MenuType>()
// 是否显示菜单信息编辑对话框
const isShowMenuInfoEditor = ref<boolean>(false)
// 是否为新增菜单信息
const isAdd = ref<boolean>(false)
// 显示新增菜单信息编辑对话框
const showAddMenuInfoEditor = () => {
  isAdd.value = true
  menuInfoForm.value = {...MenuFormDefault}
  isShowMenuInfoEditor.value = true
}
// 显示菜单信息编辑对话框
const showMenuInfoEditor = (form: MenuType) => {
  isAdd.value = false
  menuInfoForm.value = form
  isShowMenuInfoEditor.value = true
}

// 当前选中的数据行主键组成的列表
const rowKeys = ref<(number | string)[]>([])

/**
 * 菜单删除
 */
const delMenuHandler = async (delMenuIds: number[], cascade: boolean) => {
  useLoadingStore().setLoadingDesc('正在删除菜单...')
  // 发送请求删除菜单
  return await delMenus(delMenuIds, cascade)
    .then(async (res: ResType) => {
      // 删除失败
      if (!res[ResObjPropNameConst.STATUS]) return Promise.reject(res)
      // 删除成功
      useTipStore().message(res[ResObjPropNameConst.MESSAGE], TipMessageTypeConst.SUCCESS)
      // 清空选中要删除菜单的 id 列表
      rowKeys.value = []
      // 获取新的菜单信息列表
      useLoadingStore().setLoadingDesc('更新表中菜单信息...')
      const resGetMenus = await useSysMenuStore().getTableDataByReq()
      // 获取新的菜单信息列表失败
      if (!resGetMenus[ResObjPropNameConst.STATUS]) return Promise.reject(res)
    })
}
</script>

<template>
  <StnIptProvider
    class="sys-menu-page w-full h-full"
    :predefined-props="MenuIptProps"
  >
    <ManagerTable
      title="菜单管理"
      :columns="MenuTableCols"
      :data="useSysMenuStore().getTableData()"
      :loading="useSysMenuStore().getTableLoading()"
      :get-data-handler="useSysMenuStore().getTableDataByReq"
      :is-get-data-on-before-mount="useSysMenuStore().getTableData().length === 0"
      :add-handler="showAddMenuInfoEditor"
      v-model:row-keys="rowKeys"
      is-batch-del-cascade-confirm
      batch-del-cascade-confirm-text="是否级联删除子级菜单？"
      :del-handler="delMenuHandler"
      is-cascade-btn
      is-expand-all-btn
      :show-editor-handler="showMenuInfoEditor"
    >
      <template #search>
        <MenuSearch/>
      </template>
    </ManagerTable>
    <MenuInfoEditor
      v-model:show="isShowMenuInfoEditor"
      v-model:form="menuInfoForm"
      :is-add="isAdd"
    />
  </StnIptProvider>
</template>

<style scoped>

</style>
